extends Node
var consts
var base
var azurCtrl
var file = File.new()
var osName
var pc
var omgCtrl
var buffs
var plus
func _ready():
	pass
func _init():
	call_deferred("azurlaneUtilsInit")
	pass
func _connect():
	pass

func azurlaneUtilsInit():
	buffs = globalData.infoDs["g_azurlaneBuffs"]
	consts = load("%s/azurlane_ctrl/Constants.gd" % [chaData.infoDs["cex___azurtoolman"].dir]).new()
	base = globalData.infoDs["g_azurlaneBase"]
	azurCtrl = globalData.infoDs["g_azurlane"]
	osName = OS.get_name()
	if osName != "Android":
		pc = load("%s/azurlane_ctrl/PC.gd" % [chaData.infoDs["cex___azurtoolman"].dir]).new()
	if globalData.infoDs.has("g_azurlanePlus"):
		plus = globalData.infoDs["g_azurlanePlus"]
	else:
		sys.newBaseMsg("警告", "检测到未订阅[新·碧蓝航线·补充包]，部分功能将关闭！\n(注：需要在创意工坊中订阅：新·碧蓝航线·补充包MOD以开启角色立绘等功能)")
	
#角色是否在场上
func inBattle(cha):
	return cha.get_parent() is TileMap

func addShotCutToBtn(btn, keys):
	var sc = ShortCut.new()
	var key = InputEventKey.new() 
	key.scancode = keys
	sc.set_shortcut(key)
	btn.shortcut = sc
	btn.shortcut_in_tooltip = true

#根据参数创建按钮
func createItemButton(baseNode, bindInstance, text, callback, args=[], position = Vector2(90, 170), shortCut = null, bindSelf = false):
	var b = Button.new()
	if position != null:
		b.rect_position = position
	b.text = text
	if bindSelf:
		args.append(b)
	b.connect("pressed", bindInstance, callback, args)
	baseNode.add_child(b)
	if shortCut != null:
		addShotCutToBtn(b, shortCut)
	return b

func createTextureButton(baseNode, bindInstance, img, disabledImg, callback, args=[], position = Vector2(90, 170)):
	var b = TextureButton.new()
	b.rect_position = position
	b.set_normal_texture(createImageTexture(img))
	b.set_disabled_texture(createImageTexture(disabledImg))
	b.connect("pressed", bindInstance, callback, args)
	baseNode.add_child(b)
	return b

func createLabel(text, baseNode):
	var lb = Label.new()
	lb.text = text
	baseNode.add_child(lb)
	return lb

func createRichTextLabel(text, baseNode, size = Vector2(580, 50), position = null):
	var lb = RichTextLabel.new()
	lb.bbcode_text = text
	lb.bbcode_enabled = true
	lb.push_align(0)
	lb.set_custom_minimum_size(size)
	lb.name = "RichTextLabel"
	baseNode.add_child(lb)
	if position != null:
		lb.rect_position = position
	return lb
#左半场
const cellsLeft = [
	Vector2(0,0), Vector2(1,0), Vector2(2,0), Vector2(3,0), Vector2(4,0),

	Vector2(0,1), Vector2(1,1), Vector2(2,1), Vector2(3,1), Vector2(4,1),

	Vector2(0,2), Vector2(1,2), Vector2(2,2), Vector2(3,2), Vector2(4,2),

	Vector2(0,3), Vector2(1,3), Vector2(2,3), Vector2(3,3), Vector2(4,3),

	Vector2(0,4), Vector2(1,4), Vector2(2,4), Vector2(3,4), Vector2(4,4),

	Vector2(0,5), Vector2(1,5), Vector2(2,5), Vector2(3,5), Vector2(4,5)
]
#右半场单元格
const cellsRight = [
	Vector2(5,0), Vector2(6,0), Vector2(7,0), Vector2(8,0), Vector2(9,0),

	Vector2(5,1), Vector2(6,1), Vector2(7,1), Vector2(8,1), Vector2(9,1),

	Vector2(5,2), Vector2(6,2), Vector2(7,2), Vector2(8,2), Vector2(9,2),

	Vector2(5,3), Vector2(6,3), Vector2(7,3), Vector2(8,3), Vector2(9,3),

	Vector2(5,4), Vector2(6,4), Vector2(7,4), Vector2(8,4), Vector2(9,4),

	Vector2(5,5), Vector2(6,5), Vector2(7,5), Vector2(8,5), Vector2(9,5)
]

func getAllCells(team):
	if team == 1:
		return cellsLeft + cellsRight
	elif team == 2:
		return cellsRight + cellsLeft

func getAllyCells(team):
	if team == 1:
		return cellsLeft
	elif team == 2:
		return cellsRight

func getRndCell(team):
	if team == 1:
		return sys.rndListItem(cellsLeft)
	elif team == 2:
		return sys.rndListItem(cellsRight)
	else:
		return sys.rndListItem(cellsLeft + cellsRight)

func getReadyChas():
	var chas = []
	for i in sys.main.btGrid.get_children():
		if i.get_children().size() == 0:continue
		var cha:Chara = i.get_child(0)
		chas.append(cha)
	return chas

#创建技能文字特效
func createSkillTextEff(text, position):
	var eff = sys.newEff("numHit", position, false, 1)
	eff.setText(text, "#FF0099")
	eff.anim.set_speed_scale(0.2)

#人物跳跃到指定地点
func jump(target, selfCha):
	var mv = Vector2(target.cell.x ,target.cell.y)
	var vs = [Vector2(0,0),Vector2(1,0),Vector2(-1,0),Vector2(0,1),Vector2(0,-1),Vector2(1,1),Vector2(-1,1),Vector2(-1,-1),Vector2(1,-1)]
	for i in vs:
		var v = mv+i
		if sys.main.matCha(v) == null && sys.main.isMatin(v):
			if selfCha.setCell(v) :
				var pos = sys.main.map.map_to_world(selfCha.cell)
				ying(pos, selfCha)
				selfCha.position = pos
				selfCha.aiCha = null
				break
#移动特效
func ying(pos, selfCha):
	var l:Vector2 = pos - selfCha.position
	var s = 25
	var rs = preload("res://core/ying.tscn")
	var n = l.length()/s
	for i in range(n):
		var spr = rs.instance()
		sys.main.map.add_child(spr)
		spr.texture =  selfCha.img.texture
		spr.position = selfCha.position + s * (i+1) * l.normalized() - Vector2(selfCha.img.texture.get_width()/2,selfCha.img.texture.get_height())
		spr.init(255/n * i + 100)

func deleteCha(cha):
	var node = cha.get_parent()
	if node != null and cha.isItem:
		node.queue_free()
	else:
		sys.main.delMatChara(cha)

#获得steam玩家名
func getPlayerName():
	if osName == "Android":
		return base.getSetting("userName", "未知安卓玩家")
	return pc.getPlayerName()

func getPlayerId():
	if osName == "Android":return null
	return pc.getPlayerId()
#创建窗口
func createWindowDialog(baseNode, title, size = Vector2(900, 500)):
	if not is_instance_valid(baseNode):return
	var window = WindowDialog.new()
	window.set_size(size)
	window.window_title = title
	baseNode.add_child(window)
	return window
#创建滚动容器
func createScrollContainer(baseNode, size, position):
	var context = ScrollContainer.new()
	context.set_custom_minimum_size(size)
	context.rect_position = position
	baseNode.add_child(context)
	return context

func createHBox(baseNode, position = null):
	var itemBox = HBoxContainer.new()
	baseNode.add_child(itemBox)
	if position != null:
		itemBox.rect_position = position
	return itemBox

func createVBox(baseNode, position = null):
	var itemBox = VBoxContainer.new()
	baseNode.add_child(itemBox)
	if position != null:
		itemBox.rect_position = position
	return itemBox

func createGridContainer(node, size, position = null):
	var taskBox = GridContainer.new()
	taskBox.columns = size
	node.add_child(taskBox)
	if position != null:
		taskBox.rect_position = position
	return taskBox

func createLineEdit(node, size):
	var taskBox = LineEdit.new()
	taskBox.set_custom_minimum_size(size)
	node.add_child(taskBox)
	return taskBox

#获得所有单位，0全部，1敌人，2友军
func getAllChas(team = 0):
	return sys.main.getAllChas(team)
#创建图片容器
func createTextureRect(file):
	var obj = TextureRect.new()
	obj.set_texture(base.loadImg(sys.getBasePath(), file))
	return obj

func createImgBtn(file):
	var obj = ImgBtn.new()
	obj.set_texture(base.loadImg(sys.getBasePath(), file))
	return obj

func createImageTexture(file):
	return base.loadImg(sys.getBasePath(), file)

#获得角色立绘
func getCharaDrawing(cha):
	var texture = null
	var file = cha.ename
	if file == null:return null
	if plus != null:
		#从补充包中加载立绘
		texture = plus.loadDrawing(file)
	# if texture == null:
	# 	file = "drawings/" + file + "1.png"
	# 	texture = createTextureRect(file)
	return texture

#随机获得封面图
func rndCoverPic():
	return plus.rndCoverPic()

var changelog
func readChangeLog():
	if changelog == null:
		if file.file_exists(sys.getBasePath() + "/changelog.txt"):
			file.open(sys.getBasePath() + "/changelog.txt",File.READ)
			changelog=file.get_as_text()
			file.close()
			changelog.replace("**","[color=#64a6b7]").replace("##","[/color]")
		else:
			print("更新文档不存在")
			return null
	return changelog

var version:int = 0
func readVersion():
	if version == 0:
		if file.file_exists(sys.getBasePath()+"/version.txt"):
			file.open(sys.getBasePath()+"/version.txt",File.READ)
			version = int(file.get_as_text())
			file.close()
	return version

#从cha数组中获得第一个非boss角色
func getFirstFromChas(chas):
	for i in chas:
		if i.get("type") == "BOSS":continue
		return i

func lineChas(aCell, bCell, num):
	var chas = []
	var aPos = sys.main.map.map_to_world(aCell)
	var bPos = sys.main.map.map_to_world(bCell)
	var n = (bPos - aPos).normalized()
	var oldCell = null
	for i in range(num):
		var ac = sys.main.map.world_to_map(aPos)
		aPos += n * 100
		if oldCell != ac:
			oldCell = ac
			var cha = sys.main.matCha(ac)
			if cha != null:
				chas.append(cha)
			else:
				cha = sys.main.matCha(ac + Vector2(0, 1))
				if cha != null:
					chas.append(cha)
	return chas
#根据cha获得一个随机敌方单位
func getRndEnemy(cha):
	var chas = cha.getAllChas(1)
	if chas == null or chas.empty():
		return null
	else:
		return sys.rndListItem(chas)
#根据cha获得N个随机敌方单位
func getRndEnemys(cha, num):
	var result = []
	var chas = cha.getAllChas(1)
	chas.shuffle()
	for i in range(num):
		if i >= chas.size():break
		result.append(chas[i])
	return result

#根据cha获得一个随机友方单位
func getRndAlly(cha):
	return sys.rndListItem(cha.getAllChas(2))

#根据cha获得N个随机友方单位
func getRndAllys(cha, num):
	var result = []
	var chas = cha.getAllChas(2)
	chas.shuffle()
	for i in range(num):
		if i >= chas.size():break
		result.append(i)
	return result

#对字典指定字段进行加减
func dicPlus(dic, field, num):
	var f = dic.get(field)
	if f == null:
		dic[field] = num
	else:
		dic[field] = f + num
#从字典中进行检索，若没有则返回默认值
func dicGet(dic, field, default):
	var f = dic.get(field)
	if f == null:
		return default
	else:
		return f

#对字典指定字段进行append
func dicAppend(dic, field, obj):
	var f = dic.get(field)
	if f == null:
		dic[field] = [obj]
	else:
		dic[field].append(obj)

func stringToVector(cell):
	if cell is Vector2:return cell
	var x = int(cell.rsplit(",")[0].rsplit("(")[1])
	var y = int(cell.rsplit(",")[1].rsplit(")")[0])
	return Vector2(x, y)
#浮点数截取两位小数
func floatScale(num:float):
	var tmp = int(num * 100)
	return tmp/100.0

#当前是否是移动端
func isMobile():
	return osName == "Android"
	
#是否是额外不占用物品栏的道具 TODO
func isExtraItem(item):
	return item.get("itemTag") == "medic" or item.get("itemTag") == "skillbook" or item.get("itemTag") == "tmp"

func loadScript(name):
	return load(sys.getBasePath() + "/azurlane_ctrl/%s.gd" % [name]).new()

func getMouseCell():
	var pos = sys.main.map.get_local_mouse_position() + Vector2(sys.main.map.cell_size.x/2,sys.main.map.cell_size.y)
	var cell = sys.main.map.world_to_map(pos)
	return cell

func openHelpWindow(text):
	var helpPop = sys.newMsg("jiangLiMsg")
	helpPop.get_node("Panel/Label").text = "说明"
	# helpPop.print_tree_pretty()
	helpPop.get_node("Panel/Button2").hide()
	var panel = helpPop.get_node("Panel")
	var textBox = RichTextLabel.new()
	textBox.bbcode_enabled = true	
	textBox.bbcode_text = text
	textBox.margin_top = 80
	textBox.margin_left = 50
	textBox.rect_min_size = Vector2(1000,400)
	panel.add_child(textBox)
	helpPop.popup()

func newChaBt(node, id):
	var chaBt = preload("res://ui/itemBt/itemBt.tscn").instance()
	chaBt.id = id
	node.add_child(chaBt)	
	return chaBt

#给玩家新增角色	
func addPlayerCha(id):
	sys.main.player.addCha(sys.main.newChara(id))

#替换节点脚本
func changeScript(node, script):
	var prev_variables = {}
	var skip_variables = ["Script Variables", "script", "rect_global_position"]
	for property in node.get_property_list():
		var key = property.name
		if not key in skip_variables and key != "":
			prev_variables[key] = node.get(key)
	node.set_script(script)
	for property in prev_variables:
		node.set(property, prev_variables[property])		

func newChara(id, team = 1, dir = null):
	var d = dir
	if d == null:
		d = chaData.infoDs[id].dir
	var cha = preload("res://core/chara.tscn").instance()
	cha.set_script(load("{dir}/{id}/{id}.gd".format({id = id, dir = d})))
	cha.id = id
	cha.team = team
	return cha

func str2num(txt):
	if txt == null or txt == "":
		return 0
	else:
		return int(txt)


func rollItem(itm, cha, title = "结果", bonus = 0):
	var xx = sys.newMsg("jiangLiMsg")
	xx.get_node("Panel/Label").text = title
	xx.get_node("Panel/Button2").hide()
	var gachaGrid = GridContainer.new()
	gachaGrid.set_columns(5)
	gachaGrid.rect_position = Vector2(150, 75)
	xx.get_node("Panel").add_child(gachaGrid)
	if itm >= 1:
		for i in range(itm):
			var item1 = sys.newItem(itemData.rndPool.rndGet())
			sys.main.player.addItem(item1)
			var itemBt = load("res://ui/item/item.tscn").instance()
			itemBt.init(item1)
			var vbox = VBoxContainer.new()
			vbox.rect_min_size = Vector2(120, 120)
			vbox.alignment = 1
			vbox.add_child(itemBt)
			gachaGrid.add_child(vbox)
	if cha >= 1:
		for i in range(cha):
			var cha1 = getRndCha(5 + bonus)
			cha1.get_node("ui/hpBar").visible = false
			var chaBt = preload("res://ui/itemBt/itemBt.tscn").instance()
			chaBt.id = cha1.id
			sys.main.player.addCha(sys.main.newChara(cha1.id))
			gachaGrid.add_child(chaBt)
	xx.show()	
		
func getRndCha(buff = 0):
	var rngnum = sys.rndRan(1, 1000)
	var rng = ""
	if rngnum <= 5 + buff:
		rng = sys.rndListItem(chaData.infosLv4)
	elif rngnum <= 160 + buff:
		rng = sys.rndListItem(chaData.infosLv3)
	else:
		rng = sys.rndListItem(chaData.infosLv1)
	return sys.main.newChara(rng.id)

func arrayCopy(list):
	var arrs = []
	for i in list:
		arrs.append(i)
	return arrs

func toJson(data):
	return JSON.parse(data).result

#返回两个位置之间的距离
func cellRan(v, cell):
	var x =  abs(cell.x - v.x)
	var y =  abs(cell.y - v.y)
	return x + y